package de.michaelhuebl.demo.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class UrlConnectionHelper {

	/**
	 * Performs a get request with the HttpURLConnection class.
	 * 
	 * @param u Url to perform the request on.
	 * @return The Http response or null, if an error occurred.
	 */
	public String performGetRequest (String u) {
		String result = null;
		URL url;
		
		try {
			url = new URL(u);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");

			
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				Log.v("Demo", "Request executed. Result: " + conn.getResponseCode());
				result = null;
			}
			else {
				InputStream in = conn.getInputStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
				StringBuilder stringBuilder = new StringBuilder();
				String line = null;
				
				while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line + "\n");
				}
				 
				bufferedReader.close();
				result = stringBuilder.toString();
			}
			
			
		} catch (MalformedURLException e) {
			Log.v("Demo", "MalformedURLException " + e.toString());
			result = null;
		} catch (IOException e) {
			Log.v("Demo", "IOException " + e.toString());
			result = null;
		}
		
		  
		  

		
		return result;
	}
	
}
